package com.awenhui.commonweb.base.controller.vo;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import lombok.experimental.Accessors;
import lombok.experimental.SuperBuilder;
import org.apache.commons.lang3.ArrayUtils;

import java.io.Serializable;
import java.time.LocalDateTime;

import static com.awenhui.commonweb.util.CustomStringUtils.humpToUnderline;

/**
 * 分页基类vo
 *
 * @author zxiaozhou
 * @date 2020-06-22 15:27
 * @since JDK1.8
 */
@Getter
@Setter
@ToString
@EqualsAndHashCode
@SuperBuilder(toBuilder = true)
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
@Schema
public class BasePageVo implements Serializable {
    private static final long serialVersionUID = 6447362475456626689L;

    @Schema(name = "current", title = "当前页", example = "1")
    @Builder.Default
    private Long current = 1L;


    @Schema(name = "startTime", title = "开始时间", type = "string", example = "2020-12-12 11:23")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm")
    private LocalDateTime startTime;

    @Schema(name = "endTime", title = "结束时间", type = "string", example = "2020-12-12 11:23")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm")
    private LocalDateTime endTime;

    @Schema(name = "size", title = "每页条数", example = "10")
    @Builder.Default
    private Long size = 10L;

    @Schema(name = "descs", title = "降序字段列表")
    private String[] descs;

    @Schema(name = "ascs", title = "升序字段列表")
    private String[] ascs;

    @Schema(name = "getPage", title = "myBatisPlus分页信息", hidden = true)
    public <T> Page<T> getPage() {
        Page<T> page = new Page<>(this.current, this.size);
        int descLength = ArrayUtils.getLength(descs);
        int aesLength = ArrayUtils.getLength(ascs);
        // 默认排序字段
//        String createTime = "create_time";
        if (descLength > 0) {
            for (int i = 0; i < descLength; i++) {
                descs[i] = humpToUnderline(descs[i]);
            }
            page.addOrder(OrderItem.descs(this.descs));
            // 添加默认排序字段
//            page.addOrder(OrderItem.desc(createTime));
        } else if (aesLength > 0) {
            for (int i = 0; i < aesLength; i++) {
                ascs[i] = humpToUnderline(ascs[i]);
            }
            page.addOrder(OrderItem.ascs(ascs));
            // 添加默认排序字段
//            page.addOrder(OrderItem.desc(createTime));
        }
        return page;
    }
}
